const db = require("../db")
const config = require("../config")

// 获取全部文章
exports.getAllArticles = (req, res) => {
    const sql = "SELECT * FROM article WHERE is_delete = 0"
    db.query(sql, async (err, ret) => {
        if (err)
            return res.cc(err)
        res.send({
            status: 200,
            msg: "获取全部文章成功",
            data: ret,
        })
    })
}

/**
 * 通过目录id获取全部文章
 * @param req.params.cate
 */
exports.getAllArticlesByCateId = (req, res) => {
    const sql = "SELECT * FROM article WHERE cate_id = ?"
    const cateId = Number.parseInt(req.params.cate)
    db.query(sql, cateId, (err, ret) => {
        if (err)
            return res.cc(err)
        res.send({
            status: 200,
            msg: "获取当前目录下全部文章成功",
            data: ret
        })
    })
}

/**
 * 根据文章id获取文章信息
 * @param req
 */
exports.getArticleById = (req, res) => {
    const sql = "SELECT * FROM article WHERE a_id = ?"
    const a_id = Number.parseInt(req.params.a_id)
    db.query(sql, a_id, (err, ret) => {
        if (err)
            return res.cc(err)
        if (ret.length) {
            const sqlStr = "SELECT * FROM user WHERE id = ?"
            db.query(sqlStr, ret[0].author_id, (err, result) => {
                if (err)
                    return res.cc(err)
                let user = result[0]
                delete user.password
                ret[0].author = user
                res.send({
                    status: 200,
                    msg: "获取文章详细成功",
                    data: ret
                })
            })
        } else {
            res.send({
                status: 404,
                msg: "当前文章失踪啦~",
            })
        }
    })
}

// 新建文章
exports.addArticle = (req, res) => {
    const articleInfo = {
        ...req.body,
        create_time: new Date(),
        author_id: req.user.id,
        cover_img: ''
    }
    if (req.file && req.file.fieldname === 'cover_img') {
        // articleInfo.cover_img = req.file.filename
        articleInfo.cover_img = config.imgUrl + req.file.filename
    }
    console.log(req.file)
    const sql = "INSERT INTO article SET ?"
    db.query(sql, articleInfo, (err, ret) => {
        if (err)
            return res.cc(err)
        if (ret.affectedRows !== 1)
            return res.cc("新增文章失败")
        res.cc("新增文章成功", 200)
    })
}